package com.vincce.sport.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.vincce.sport.core.utils.Constant;
import com.vincce.sport.core.utils.SimpleStorageClient;
import com.vincce.sport.entity.Activity;
import com.vincce.sport.entity.ActivityBrand;
import com.vincce.sport.entity.ActivityOption;
import com.vincce.sport.entity.ActivityQuestion;
import com.vincce.sport.entity.ActivityUser;
import com.vincce.sport.entity.Advert;
import com.vincce.sport.entity.User;
import com.vincce.sport.mapper.ActivityBrandMapper;
import com.vincce.sport.mapper.ActivityMapper;
import com.vincce.sport.mapper.ActivityOptionMapper;
import com.vincce.sport.mapper.ActivityQuestionMapper;
import com.vincce.sport.mapper.ActivityUserMapper;
import com.vincce.sport.mapper.AdvertMapper;


@Controller
@RequestMapping("/activityFore")
public class ActivityForeController extends IndexController{
	@Resource
	private ActivityMapper activityMapper;
	
	@Resource
	private ActivityQuestionMapper activityQuestionMapper;
	
	@Resource
	private ActivityOptionMapper activityOptionMapper;
	
	@Resource
	private ActivityUserMapper activityUserMapper;
	
	@Resource
	private ActivityBrandMapper activityBrandMapper;
	
	@Resource
	private AdvertMapper advertMapper;
	

	
	@RequestMapping("/activityDetail")
	public String activityDetail(Model model, Integer activityId, Integer brandId){
		Activity activity = new Activity();
		if(brandId!=null && !brandId.equals("")){
			activity.setStatus("1");
			activity.setBrandId(brandId);
			List<Activity> activitylist = activityMapper.findActivityByOne(activity);
			if(activitylist!=null && activitylist.size()>0){
				activity = activitylist.get(0);
			}
		} else if(activityId!=null && !activityId.equals("")){
			activity = activityMapper.findActivityById(activityId);
		}
		model.addAttribute("activity", activity);
		return "/foreground/activityDetail";
	}
	 
	@RequestMapping("/activityList")
	public String activityList(Model model, HttpServletRequest request, Integer brandId, Integer activityId, String type) throws ParseException{
		User userInfo=(User) request.getSession().getAttribute(Constant.T_USER);
//		if(userInfo != null){
			Activity activity = new Activity();
			activity.setStatus("1");
			if(type!=null && type.equals("2") && brandId != null && !brandId.equals("")){
				activity.setBrandId(brandId);
				ActivityBrand activityBrand = activityBrandMapper.findActivityBrandById(brandId);
				activityBrand.setLogUrl(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+activityBrand.getLogUrl(), "ori"));
				model.addAttribute("activityBrand", activityBrand);
			} else{
				type = "1";
			}
			List<Activity> activitylist = activityMapper.findActivityByOne(activity);
			
			if(activitylist!=null && activitylist.size()>0){
				if(activityId != null && !activityId.equals("")){
					activity = activityMapper.findActivityById(activityId);
				} else{
					activity = activitylist.get(0);
				}
				
				if(activity.getImgPath()!=null && !activity.getImgPath().equals("")){
					activity.setImgPath(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+activity.getImgPath(), "ori"));
				}
				ActivityQuestion activityQuestion = new ActivityQuestion();
				activityQuestion.setActivityId(activity.getId());
				List<ActivityQuestion> activityQuestionList = activityQuestionMapper.findActivityQuestionByOne(activityQuestion);
				if(activityQuestionList!=null && activityQuestionList.size()>0){
					//获取活动第一个问题的选项
					for(ActivityQuestion aql:activityQuestionList){
						List<ActivityUser> activityUserList = new ArrayList<ActivityUser>();
						if(userInfo != null){
							ActivityUser activityUser = new ActivityUser();
							activityUser.setActivityId(activity.getId());
							activityUser.setQuestionId(aql.getId());
							activityUser.setUserName(userInfo.getUserName());//当前用户
							activityUserList = activityUserMapper.findActivityUserByOne(activityUser);
						}
						if(activityUserList!=null && activityUserList.size()>0){
//							for(int i=0;i<activityUserList.size();i++){
//								if(i==0){
//									aql.setAnswer(activityQuestionList.get(i).getAnswer());
//								} else{
//									activityUserMapper.deleteById(activityUserList.get(i).getId());
//								}
//							}
						} else{
							ActivityOption activityOption = new ActivityOption();
							activityOption.setQuestionId(aql.getId());
							List<ActivityOption> activityOptionList = activityOptionMapper.findActivityOptionByOne(activityOption);
//							activityQuestionList.get(0).setActivityOptionList(activityOptionList);
							activityQuestion = aql;
							activityQuestion.setActivityOptionList(activityOptionList);
							break;
						}
					}
				}
				if(type!=null && type.equals("2")){
					for(Activity al:activitylist){
						if(al.getImgPath() != null && !al.equals("")){
							if(!al.getImgPath().contains(SimpleStorageClient.REQUEST_URI2_PREFIX)){
								al.setImgPath(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+al.getImgPath(), "ori"));
							}
						}
					}
					/*if(activity.getImgPath()!=null && !activity.getImgPath().equals("")){
						activity.setImgPath(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+activity.getImgPath(), "ori"));
					}*/
					model.addAttribute("activitylist", activitylist);
				} else{
					Advert advert = new Advert();
					advert.setName("奖品类活动");
					List<Advert> advertList1 = advertMapper.findAdvertByOne(advert);
					if(advertList1==null){
						advertList1 = new ArrayList<Advert>();
					} else{
						for(Advert al:advertList1){
							if(al.getAdvertImg()!=null && !al.getAdvertImg().equals(""))
								al.setAdvertImg(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+al.getAdvertImg(), "ori"));
						}
					}
					model.addAttribute("advertList1", advertList1);
					advert.setName("机遇类活动");
					List<Advert> advertList2 = advertMapper.findAdvertByOne(advert);
					if(advertList2==null){
						advertList2 = new ArrayList<Advert>();
					} else{
						for(Advert al:advertList2){
							if(al.getAdvertImg()!=null && !al.getAdvertImg().equals(""))
								al.setAdvertImg(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+al.getAdvertImg(), "ori"));
						}
					}
					model.addAttribute("advertList2", advertList2);
					List<ActivityBrand> activityBrandList = activityBrandMapper.queryByActivityBrandAll();
					if(activityBrandList==null){
						activityBrandList = new ArrayList<ActivityBrand>();
					} else{
						for(ActivityBrand abl:activityBrandList){
							abl.setLogUrl(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+abl.getLogUrl(), "ori"));
						}
					}
					model.addAttribute("activityBrandList", activityBrandList);
				}
				if(activityQuestionList==null){
					activityQuestionList = new ArrayList<ActivityQuestion>();
				}
				model.addAttribute("activityQuestion", activityQuestion);
				model.addAttribute("activityQuestionList", activityQuestionList);
				model.addAttribute("status", "1");
			} else{
				model.addAttribute("status", "2");
			}
			model.addAttribute("activity", activity);
			model.addAttribute("type", type);
			return "/foreground/activityList";
//		} else{
//			return sportIndex(model, request, "请先登录！");
//		}
	}
	
	@RequestMapping("/getQuestionOption")
	@ResponseBody
	public String getQuestionOption(Model model, HttpServletRequest request, Integer questionId){
		Boolean flag=false;
		Map<String, Object> result = new HashMap<String, Object>();
		User userInfo=(User) request.getSession().getAttribute(Constant.T_USER);
		
		ActivityQuestion activityQuestion = activityQuestionMapper.findActivityQuestionById(questionId);
		if(activityQuestion!=null){
			ActivityOption activityOption = new ActivityOption();
			activityOption.setQuestionId(questionId);
			List<ActivityOption> activityOptionList = activityOptionMapper.findActivityOptionByOne(activityOption);
			activityQuestion.setActivityOptionList(activityOptionList);
			
			//获取用户答案
			ActivityUser activityUser = new ActivityUser();
			activityUser.setQuestionId(questionId);
			
			if(userInfo != null){
				activityUser.setUserName(userInfo.getUserName());//当前用户
			}
			List<ActivityUser> activityUserList = activityUserMapper.findActivityUserByOne(activityUser);
			if(activityUserList!=null && activityUserList.size()>0){
				for(int i=0;i<activityUserList.size();i++){
					if(i==0){
						activityQuestion.setAnswer(activityUserList.get(i).getAnswer());
					} else{
						activityUserMapper.deleteById(activityUserList.get(i).getId());
					}
				}
			}
			flag = true;
		}
		if(activityQuestion==null){
			activityQuestion = new ActivityQuestion();
		}
		result.put("activityQuestion", activityQuestion);
		result.put("suc", flag);
        return JSON.toJSONString(result);
	}
	
	@RequestMapping("/checkAnswer")
	@ResponseBody
	public String checkAnswer(Model model, HttpServletRequest request, String activityIds, 
			String questionIds, String questions, String questionOrders, String answers){
		Map<String, Object> result = new HashMap<String, Object>();
		User userInfo=(User) request.getSession().getAttribute(Constant.T_USER);
		if(userInfo == null){
			result.put("suc", false);
	        return JSON.toJSONString(result);
		}
		String[] activityId = activityIds.split("&&");
		String[] questionId = questionIds.split("&&");
		String[] question = questions.split("&&");
		String[] questionOrder = questionOrders.split("&&");
		String[] answer = answers.split("&&");
		
		ActivityUser activityUser = null;
		String req = "";
		for(int i=0;i<activityId.length;i++){
			activityUser = new ActivityUser();
			activityUser.setUserName(userInfo.getUserName());
			activityUser.setActivityId(Integer.parseInt(activityId[i]));
			activityUser.setQuestionId(Integer.parseInt(questionId[i]));
			activityUser.setQuestion(question[i]);
			activityUser.setQuestionOrder(Integer.parseInt(questionOrder[i]));
			activityUser.setAnswer(answer[i]);
			
			List<ActivityUser> activityUserList = activityUserMapper.findActivityUserByOne(activityUser);
			if(activityUserList!=null && activityUserList.size()>0){
				result.put("suc", false);
		        return JSON.toJSONString(result);
			} else{
				req = quesAnswer(model, request, activityUser);
			}
		}
        return req;
	}
	
	@RequestMapping("/quesAnswer")
	@ResponseBody
	public String quesAnswer(Model model, HttpServletRequest request, ActivityUser activityUser){
		Long count = 0l;
		Map<String, Object> result = new HashMap<String, Object>();
		//TODO 放入userId
		User userInfo=(User) request.getSession().getAttribute(Constant.T_USER);
		if(userInfo == null){
			result.put("suc", count > 0 ? true : false);
	        return JSON.toJSONString(result);
		}
		activityUser.setUserName(userInfo.getUserName());//当前用户
		List<ActivityUser> activityUserList = activityUserMapper.findActivityUserByOne(activityUser);
		if(activityUserList!=null && activityUserList.size()>0){
			for(int i=0;i<activityUserList.size();i++){
				if(i==0){
					activityUser.setId(activityUserList.get(i).getId());
					count = activityUserMapper.updateActivityUser(activityUser);
				} else{
					activityUserMapper.deleteById(activityUserList.get(i).getId());
				}
			}
		} else{
			count = activityUserMapper.insertActivityUser(activityUser);
		}
		
		
		result.put("suc", count > 0 ? true : false);
        return JSON.toJSONString(result);
	}
}
